package com.zhuhjay.ruiji.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhuhjay.ruiji.common.R;
import com.zhuhjay.ruiji.domain.Category;
import com.zhuhjay.ruiji.service.ICategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author ZhuHJay
 * @date 2022/5/16 13:53
 */
@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {

    private final ICategoryService categoryService;
    public CategoryController(ICategoryService categoryService) {
        this.categoryService = categoryService;
    }

    @PostMapping
    public R<String> save(@RequestBody Category category){
        categoryService.save(category);
        return R.success("添加成功");
    }

    @GetMapping("/page")
    public R<Page<Category>> page(@RequestParam(name = "page", defaultValue = "1", required = false) Integer page,
                                  @RequestParam(name = "pageSize", defaultValue = "10", required = false) Integer pageSize){
        Page<Category> categoryPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Category::getSort);
        categoryService.page(categoryPage, queryWrapper);
        return R.success(categoryPage);
    }

    @DeleteMapping
    public R<String> delete(Long id){
        // 判断该分类是否绑定套餐
        categoryService.checkRemove(id);
        return R.success("删除成功");
    }

    @PutMapping
    public R<String> update(@RequestBody Category category){
        categoryService.updateById(category);
        return R.success("修改成功");
    }

    @GetMapping("/{id}")
    public R<Category> query(@PathVariable("id") Long id){
        return R.success(categoryService.getById(id));
    }

    @GetMapping("/list")
    public R<List<Category>> list(String type,
                        @RequestParam(name = "page", defaultValue = "1", required = false) Integer page,
                        @RequestParam(name = "pageSize", defaultValue = "1000", required = false) Integer pageSize){
        Page<Category> categoryPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(type != null, Category::getType, type)
                    .orderByDesc(Category::getUpdateTime)
                    .orderByAsc(Category::getSort);
        categoryService.page(categoryPage, queryWrapper);
        return R.success(categoryPage.getRecords());
    }

}
